<template>
  <!-- <el-table-column type="selection" width="55" /> -->
  <el-table
    v-loading="loading"
    :data="props.list"
    row-key="id"
    calss="orderTable"
    cell-class-name="tableCell"
    row-class-name="tableRow"
    :span-method="spanMethod"
    ref="tableRef"
    @selection-change="handleSelectionChange"
     height="80vh"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column class-name="mergeRow" width="1">
      <template #default="{ row }">
        <div class="relative flex" >
          <span
            class="ml-10px text-[#231E47] text-[14px] cursor-pointer mr-20px py-[8px] font-normal"
            v-copyText="row.orderNo"
          >
            订单号：{{ row.orderNo }}
            <Icon icon="ep:copy-document" :size="12" class="cursor-pointer" />
          </span>
          <span class="text-[#231E47] text-[14px] py-[8px] font-normal">
            创建时间：{{ formatDate(row.createTime) }}
          </span>
          <span
            class="block w-[1px] h-[18px] py-[8px] bg-[#231E47] relative mx-[20px] top-[10px] line"
            style="display: inline-block"
          ></span>
          <span class="mr-20px text-[#231E47] text-[14px] py-[8px] font-normal">
            修改时间：{{ formatDate(row.updateTime) }}
          </span>
        </div>
        <!-- <div
            class="ml-auto flex justify-between shrink-0 items-center w-[160px] text-[14px] font-normal right-[20px] px-[10px] btn py-[8px] btnfixed"
          >
            <span class="text-[#3721FF] pl-[12px] cursor-pointer">编辑</span>
            <span class="text-[#3721FF] pl-[12px] cursor-pointer">详情</span>
            <span class="text-[#3721FF] pl-[12px] cursor-pointer">备注</span>
          </div> -->
      </template>
    </el-table-column>
    <el-table-column label="售后订单" min-width="300">
      <template #default="{ row }">
        <div class="mt-[45px] overflow-hidden" :class="row.isExpland ? 'noMaxH' : 'max-h-[120px]'">
          <div class="flex items-center info">
            <div class="w-[86px] h-[86px] mr-[10PX] left">
              <el-image
                  :src="row.cover"
                  class="!h-[86px] !w-[86px] roundec-[12px]"
                  fit="contain"
                  @click="imagePreview(row.cover)"
                >
                  <template #error>
                    <div class="image-slot">
                      <icon icon="ep:picture" />
                    </div>
                  </template>
                </el-image>
            </div>
            <div class="right">
              <div class="text-[14px] text-[#dfc437] pt-[8px]">{{ row.thaliName }}</div>
              <div class="flex pt-[4px] pb-[4px]  flex-wrap" v-for="(item, index) in row.detailList" :key="index" :style="index < row.detailList.length - 1 ? 'border-bottom:1px dashed #999' : ''">
                  <div class="cursor-pointer info"  @click="openUrl(row.orderLink)">
                    <!-- <ElTooltip :content="item.productName" placement="top"> -->
                      <!-- overflow-ellipsis -->
                      <div class="text-cut text-[12PX] w-[180PX] text-[#077BFF]">
                        {{ item.productName }}
                      </div>
                    <!-- </ElTooltip> -->
                    <div class="flex items-center  text-[12px] numbox"> <span class="text-[#231E47]">({{item.sku}})</span> * <span class="text-[#999]">{{ item.number }}</span> </div>
                    <!-- <div class="text-[#999] text-[14px] numbox"> 商品ID: {{ item.productId }} </div> -->
                  </div>
              </div>
            </div>
          </div>
          
        </div>
        <div class="cursor-pointer text-[#077BFF]" @click="changeExpland(row)"> {{ row.isExpland ? '收起' : '展开' }}</div>
      </template>
    </el-table-column>
    <el-table-column label="关联销售订单/线上订单号" min-width="190">
      <template #default="{ row }">
        <!-- row.adjustPrice没用，纯占位，不输出row会报错 -->
        {{ row.orderNo }}
      </template>
    </el-table-column>
    <el-table-column label="地区" width="180" :show-overflow-tooltip="true">
      <template #default="{ row }">
        <!-- <dict-tag
              :type="DICT_TYPE.TRADE_ORDER_ITEM_AFTER_SALE_STATUS"
              :value="row.afterSaleStatus"
            /> -->
        {{ row.areaName }}
      </template>
    </el-table-column>
    <el-table-column label="下单信息" min-width="200">
      <template #default="scope">
        <div class="pt-[40px]">
          <div>买家：{{ scope.row.customerName }}</div>
          <div>买家手机：{{ scope.row.customerPhone }}</div>
          <div class="">
            <img :src="StarPng" class="w-[14px] h-14px" alt="" v-if="scope.row.remoteFlag" />
            地址：{{ scope.row.detailAddress }}{{ scope.row.houseNumber }}
          </div>
        </div>
        <!-- 快递发货  -->
        <!-- <div v-if="scope.row.deliveryType === DeliveryTypeEnum.EXPRESS.type" class="flex flex-col">
          <span>买家：{{ scope.row.user?.nickname }}</span>
          <span>
            收货人：{{ scope.row.receiverName }} {{ scope.row.receiverMobile }}
            {{ scope.row.receiverAreaName }} {{ scope.row.receiverDetailAddress }}
          </span>
        </div> -->
        <!-- 自提  -->
        <!-- <div v-if="scope.row.deliveryType === DeliveryTypeEnum.PICK_UP.type" class="flex flex-col">
          <span>
            门店名称：
            {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.name }}
          </span>
          <span>
            门店手机：
            {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.phone }}
          </span>
          <span>
            自提门店:
            {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.detailAddress }}
          </span>
        </div> -->
      </template>
    </el-table-column>
    <el-table-column label="物流方式" min-width="100">
      <template #default="{ row }">
        {{ row.logisticsMethodName }}
      </template>
    </el-table-column>
    <el-table-column label="订单总金额" min-width="120">
      <template #default="{ row }"> 
      <div>{{ row.currencySymbol }} {{ row.orderAmount }} </div>
      <div v-if="row.orderFreight " class="text-[12px] text-[#666]">(含运费{{ row.currencySymbol }} {{ row.orderFreight }})</div>  
      <div>￥ {{ row.orderAmountCny || '-' }}</div>
      </template>
    </el-table-column>
    <el-table-column label="订单状态" width="120" align="center">
      <template #default="scope">
        <div class="flex items-center justify-center statusbox">
          <div
            class="px-[7px] py-[2px] flex items-center rounded-[5px]"
            :style="`background-color:${afterOrderStatus[scope.row.status].bgColor}`"
          >
            <div class="w-[12px] h-[12px] rounded-[50%] relative mr-[4px] icon">
              <img
                :src="afterOrderStatus[scope.row.status].icon"
                class="absolute top-0 left-0 object-contain w-full h-full"
              />
            </div>
            <div
              class="text-[12px] status txt"
              :style="`color:${afterOrderStatus[scope.row.status].color}`"
            >
              {{ afterOrderStatus[scope.row.status].name }}</div
            >
          </div>
        </div>

        <!-- <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" /> -->
      </template>
    </el-table-column>
    <el-table-column label="部门/人员" width="180">
      <template #default="{ row }">
        <div>{{ `${row.deptName||'-'}/${row.createName||'-'}` }}</div>
       
      </template>
    </el-table-column>
    <el-table-column label="留言/备注" min-width="170" :show-overflow-tooltip="true">
      <template #default="{ row }">
        <!-- <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" /> -->
        <div class="flex items-start items">
          <div class="shrink-0 label">留言：</div>
          <div class="val">{{ row.message }}</div>
        </div>
        <div class="flex items-start items">
          <div class="shrink-0 label">备注：</div>
          <div class="val">{{ row.remark }}</div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="创建时间/更新时间" min-width="180">
      <template #default="{ row }">
        {{ formatDate(row.createTime) }} / {{ formatDate(row.updateTime) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="140">
      <template #default="scope">
        <div class="flex  w-full">
          <div
            class="text-[#3721FF] text-[12px] cursor-pointer mr-[10px]"
            @click="handleDetails(scope.row)"
          >
            详情
          </div>
          <div
            class="text-[#3721FF] text-[12px] cursor-pointer mr-[10px]"
            @click="handelRemark(scope.row)"
          >
            备注
          </div>
          <div
            class="text-[#FF6D21] text-[12px] cursor-pointer mr-[10px]"
            @click="handleCancel(scope.row)"
            v-if="scope.row.status != 11 && scope.row.status != 12"
          >
            作废
          </div>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <OrderDetails ref="orderDetailsRef" :orderNo="curOrderId" />
  <Remark
    ref="remarkRef"
    :remarkOrderNo="remarkOrderId"
    :remarkInfo="remarkInfo"
    @updateRemark="updateRemark"
  />
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { DeliveryTypeEnum } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { floatToFixed2 } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { OrderVO } from '@/api/mall/trade/order'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import type { DeliveryPickUpStoreVO } from '@/api/mall/trade/delivery/pickUpStore'
import { afterOrderStatus } from '@/utils/order'
import StarPng from '@/assets/mall/trade/order/star.png'
import OrderDetails from './OrderDetails.vue'
import Remark from './Remark.vue'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const message = useMessage() // 消息弹窗

const { loadStart, loadDone } = usePageLoading()

defineOptions({ name: 'OrderTableColumn' })

const props = defineProps<{
  list: OrderVO[]
}>()

const emit = defineEmits(['updateList', 'selectionChange'])

const loading = ref(false)

const orderDetailsRef = ref<InstanceType<typeof OrderDetails> | null>(null)

const remarkRef = ref<InstanceType<typeof Remark> | null>(null)

const tableRef = ref<TableInstance | null>(null)

const headerStyle = ({ row, columnIndex }: any) => {
  // 表头第一行第一列占 8
  if (columnIndex === 0) {
    row[columnIndex].colSpan = 8
  } else {
    // 其余的不要
    row[columnIndex].colSpan = 0
    return {
      display: 'none'
    }
  }
}

const selectAll = ref(false)
const selectAllIndeterminate = ref(false)
const selectedRows = ref<any[]>([])

const curOrderId = ref()

const remarkOrderId = ref()

const remarkInfo = ref()

interface SpanMethodProps {
  row: TradeOrderApi.OrderItemRespVO
  column: TableColumnCtx<TradeOrderApi.OrderItemRespVO>
  rowIndex: number
  columnIndex: number
}

type spanMethodResp = number[] | { rowspan: number; colspan: number } | undefined
const spanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps): spanMethodResp => {
  // const len = props.list.find(
  //   (order) => order.items?.findIndex((item) => item.id === row.id) !== -1
  // )?.items?.length
  // const len = 8
  // // 要合并的列，从零开始
  // const colIndex = [3, 4, 5, 6, 7]
  // if (colIndex.includes(columnIndex)) {
  //   // 除了第一行其余的不要
  //   if (rowIndex !== 0) {
  //     return {
  //       rowspan: 0,
  //       colspan: 0
  //     }
  //   }
  //   // 动态合并行
  //   return {
  //     rowspan: len!,
  //     colspan: 1
  //   }
  // }
  if (columnIndex === 7) {
    return [1, 1] // 第一列合并所有行
  }
  return [1, 1] // 其他列正常显示
}

/** 解决 ref 在 v-for 中的获取问题*/
const setOrderTableRef = (el: TableInstance) => {
  if (!el) return
  // 只要第一个表也就是开始的第一行
  if (el.tableId !== 'el-table_2') {
    return
  }
  tableHeadWidthAuto(el)
}
// 头部 col 宽度初始化
const orderTableHeadWidthList = ref([300, 150, 120, 160, 120, 120, 120, 160])
// 头部宽度自适应
const tableHeadWidthAuto = (el: TableInstance) => {
  const columns = el.store.states.columns.value
  if (columns.length === 0) {
    return
  }
  columns.forEach((col: TableColumnCtx<TableInstance>, index: number) => {
    if (col.realWidth) {
      orderTableHeadWidthList.value[index] = col.realWidth
    }
  })
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/**
 * 全选切换
 */
const handleSelectAll = () => {
  const allSelected = selectAll.value // 获取全选状态
  selectAllIndeterminate.value = false
  selectedRows.value = allSelected
    ? props.list.map((order) => {
        return order
      })
    : [] // 取消所有选中
  // 更新每个订单的选中状态
  props.list.forEach((order) => {
    order.selected = allSelected
  })
}

/**
 * 单选选中切换
 */
const handleSelectItems = (row) => {
  const allSelected = props.list.every((order) => order.selected)
  selectAll.value = allSelected

  // 更新 indeterminate 状态
  const someSelected = props.list.some((order) => order.selected)
  selectAllIndeterminate.value = someSelected && !allSelected
}

/**
 * 获取选中行信息
 */
const handleSelectionChange = (val) => {
  selectedRows.value = val
  emit('selectionChange', val)
}

/**
 * 显示详情
 */
const handleDetails = (row) => {
  curOrderId.value = row.orderNo
  orderDetailsRef.value?.show()
}

/**
 * 显示备注
 */
const handelRemark = (row) => {
  remarkOrderId.value = row.orderNo
  remarkInfo.value = row.remark
  remarkRef.value?.show()
}

/**
 * 修改备注
 */
const updateRemark = async (val: any) => {
  try {
    loadStart()
    await TradeOrderApi.updateOrderRemarkNew({ orderNo: val.orderNo, remark: val.remark })
    ElMessage.success('备注修改成功')
    emit('updateList')
  } catch (error) {
  } finally {
    remarkRef.value?.hide()
    loadDone()
  }
}

const handleCancel = async (row) => {
  tableRef.value?.clearSelection()
  tableRef.value?.toggleRowSelection(row, true)
  try {
    await message.confirm('确定要作废该订单吗？')
    loadStart()
    await TradeOrderApi.updateOrderStatus({ orderNo: [row.orderNo], status: 12 })
    ElMessage.success('订单作废成功')
    emit('updateList')
  } catch (error) {
  } finally {
    loadDone()
  }
}


const openUrl = (url: string) => {
  //校驗url
  if(!url) return
  if( url.indexOf('http') > -1 || url.indexOf('https') > -1){
    window.open(url)
  }else{
    ElMessage.error('链接不合法')
  }
}
/**
 * 展开/收起
*/
const changeExpland = (row) => {
  row.isExpland = !row.isExpland
}

</script>
<style lang="scss" scoped></style>
